let App = getApp();

Page({
  data: {
    searchColor: "rgba(0,0,0,0.4)",
    searchSize: "15",
    searchName: "搜索",
    scrollHeight: null,
    showView: false,
    arrange: "",
    sortPrice: false,   // 价格从低到高
    orderType: '',
    option: {},
    list: [],
    noList: true,
    no_more: false,
    first_array: [],
    first_value:[],
    index:0,
    sindex:0,
    id:0,
    sid:0,
    second_array:[],
    second_value:[],
    pageNumber: 1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (option) {
    console.log(option,'op')
    const id = option.id
    let _this = this;
    //获取一级分类
    App._get('/mapi/category/index',{pid:1},function(resault){
        console.log(resault)
        resault.data.unshift({id:0,title:'全部素材'})
        const list = resault.data.map((item)=>{
          return item.title
        })
         const index = resault.data.findIndex((item)=>{
           console.log(item)
         return item.id == id
         });
         console.log(index,'index')
         if(index){
           _this.setData({index:index})
         }
        _this.setData({'first_array':list,'first_value':resault.data})
        _this.getProductList(true)
    })


    // 设置商品列表高度
    _this.setListHeight();

    // 记录option
    _this.setData({ option }, function () {
      // 获取商品列表
      _this.getProductList(true);
    });
    wx.showShareMenu({
      withShareTicket:true,
      menus:['shareAppMessage','shareTimeline']
      })

  },
  bindPickerChange: function(e) {
    const _this = this
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
    // 查询二级分类
    console.log(this.data.first_value[e.detail.value])
    if(this.data.first_value[e.detail.value].children){
     const list = this.data.first_value[e.detail.value].children.map(item=>item.title)
     const list_value = [...this.data.first_value[e.detail.value].children]
     list.unshift('全部')
     list_value.unshift({id:0,title:'全部素材'})
      this.setData({'second_array':list,second_value:list_value,sindex:0})
    }
    this.setData({'id':this.data.first_value[e.detail.value].id})
    this.getProductList(true)
   
  },
    sbindPickerChange: function(e) {
      console.log('picker发送选择改变，携带值为', e.detail.value)
      const id = this.data.second_value[e.detail.value].id
      this.setData({
        sindex: e.detail.value,
        sid:id
      })
      this.getProductList(true)
    },
  /**
   * 获取商品列表
   */
  getProductList: function (is_super, pageNumber) {
    let _this = this;
    console.log('success：'+_this.data.orderType);
    console.log('success:'+_this.data.option.search );
    console.log(_this.data.id)
    App._get('/mapi/source/index', {
      page: pageNumber || 1,
      category_id_2:_this.data.id,
      category_id_3:_this.data.sid,
      search:_this.data.searchValue||''
    }, function (result) {
      let resultList = result.data
        , dataList = _this.data.list;
        console.log(is_super,'is')
        if(is_super){
          _this.setData({ 'list':resultList });
        }else{
          _this.setData({ 'list': dataList.concat(resultList) });
        }
    });
  },
  getSearchContent(e) {
    this.data.searchValue = e.detail.value;

  },
  /**
   * 设置商品列表高度
   */
  setListHeight: function () {
    let _this = this;
    wx.getSystemInfo({
      success: function (res) {
        _this.setData({
          scrollHeight: res.windowHeight - 90,
        });
      }
    });
  },

  /**
   * 切换排序方式
   */
  switchSortType: function (e) {
    let _this = this
      , orderType
      , newSortType = e.currentTarget.dataset.type
      , newSortPrice = newSortType === 'price' ? !_this.data.sortPrice : true;
    
    if (newSortType === 'price') {
      orderType = newSortPrice ? 'PRICE_ASC' : 'PRICE_DESC';
    } else if (newSortType === 'sales') {
      orderType = 'SALES_DESC';
    } else {
      orderType = 'TOP_DESC';
    }

    _this.setData({
      list: {},
      pageNumber: 1,
      sortPrice: newSortPrice,
      orderType: orderType
    }, function () {
      // 获取商品列表
      _this.getProductList(true);
    });
  },


  /**
   * 切换列表显示方式
   */
  onChangeShowState: function () {
    let _this = this;
    _this.setData({
      showView: !_this.data.showView,
      arrange: _this.data.arrange ? "" : "arrange"
    });
  },

  /**
   * 下拉到底加载数据
   */
  bindDownLoad: function () {
    // 已经是最后一页
    if (this.data.pageNumber >= this.data.lastPage) {
      this.setData({ no_more: true });
      return false;
    }
    this.getProductList(false, ++this.data.pageNumber);
  },

  /**
   * 设置分享内容
   */
  onShareAppMessage: function (e) {
    console.log(e.target)
    const id = e.target.dataset.id
    // 构建页面参数
    let _this = this;
    return {
      title:'半亩花田' ,
      path: "/pages/product/detail?id=" + id
    };
  },


    /**
   * setlike
   */

  setlike: function (event) {
    console.log(event, '--event')
    const _this = this
    const source_id = event.currentTarget.dataset.source_id
    const index = event.currentTarget.dataset.index
    console.log(source_id, '--source_id')
    App._get('/mapi/user_operate/dolike', { source_id: source_id }, function (result) {
      if (result.code == 200) {
        const products = _this.data.products;
        if (products[index].user_like_state==0) {
          products[index].like_num += 1;
          products[index].user_like_state = 1
          _this.setData({
            products: products
          });
          wx.showToast({
            title: '收藏成功',
          })
        }else{
          products[index].like_num -= 1;
          products[index].user_like_state = 0;
          _this.setData({
            products: products
          });
          wx.showToast({
            title: '取消收藏',
          })
        }
      }else{
        // 请登录
       App.doLogin()

      }
    })
  },
  setcollect: function (event) {
    const _this = this
    const source_id = event.currentTarget.dataset.source_id
    const index = event.currentTarget.dataset.index
    App._get('/mapi/user_operate/docollect', { source_id: source_id }, function (result) {
      if (result.code == 200) {
        const products = _this.data.products;
        if (products[index].user_collect_state==0) {
          products[index].collect_num += 1;
          products[index].user_collect_state = 1
          _this.setData({
            products: products
          });
          wx.showToast({
            title: '收藏成功',
          })
        }else{
          products[index].collect_num -= 1;
          products[index].user_collect_state = 0;
          _this.setData({
            products: products
          });
          wx.showToast({
            title: '取消收藏',
          })
        }
      }else{
        App.doLogin()
      }
    })
  },
  download: function (file) {
    App.download()
  },
  /**
   * 图片预览
   */
  preview: function(event){
    const src = event.currentTarget.dataset.src
    wx.previewImage({
      urls: [src],
    })
  }
  

});
